# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '25691442': {  # 一付通 支付宝 2.3% 100-10000 dwc
        'API_KEY': '0e2ac0938cce87350befd5a358670772',
        'gateway': 'https://yhf.959pb.cn/connect/httpapi/startapi',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'SignKey' and k != 'Sign_Type' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:-1] + '%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['SignKey']
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yifutongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    elif service == 'wechat':
        return 'wechat'
    return 'alipay'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Appid', app_id),
        ('Version', '1.0.0.1'),
        ('Out_Trade_No', str(pay.id)),
        ('Total_Amount', '%.2f' % pay_amount),
        ('Subject', 'charge'),
        ('Method', _get_pay_type(service)),
        ('Notify_Url', '{}/pay/api/{}/yifutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameters = OrderedDict((
        ('TransCode', '130101'),
        ('Body', json.dumps(parameter_dict)),
    ))
    parameters['SignKey'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yifutongpay create: %s, order_id is: %s", json.dumps(parameters), parameter_dict['Out_Trade_No'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameters, headers=headers, timeout=5)
    _LOGGER.info('yifutongpay create rsp, %s', response.text)
    return {'charge_info': json.loads(response.text)['Body']['Pay_Url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("yifutongpay notify data: %s", dict(request.POST.iteritems()))
    data = dict(request.POST.iteritems())
    verify_notify_sign(data, api_key)
    pay_id = data['Out_Trade_No']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yifutongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['Status'])
    trade_no = ''
    total_fee = float(data['Real_Money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 1 交易成功
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('yifutongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass